<template>
  <div class="h-full w-full p-5">
    <div class="card-box h-full">
      <div class="product-list-container min-h-full">
        <!-- 页面标题和操作区 -->
        <div class="page-header">
          <h1 class="page-title">订单管理</h1>
        </div>

        <!-- 筛选区 -->
        <el-card class="filter-card">
          <div class="filter-group">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索订单编号"
              clearable
              class="search-input"
              @keyup.enter="handleSearch"
              @clear="handleSearch"
            >
              <template #append>
                <el-button @click="handleSearch">
                  <IconifyIcon icon="material-symbols:search" />
                </el-button>
              </template>
            </el-input>

            <el-select
              v-model="filterState"
              placeholder="请选择订单状态"
              clearable
              class="status-filter"
              @change="handleSearch"
            >
              <el-option
                v-for="status in Object.values(ORDER_STATUS)"
                :key="status.state"
                :label="status.msg"
                :value="status.state"
              />
            </el-select>

            <el-button @click="resetFilters">重置</el-button>
          </div>
        </el-card>

        <!-- 订单列表 -->
        <el-card class="table-card">
          <el-table
            :data="tableData"
            border
            stripe
            :loading="tableLoading"
            empty-text="暂无订单数据"
            style="width: 100%"
          >
            <el-table-column
              type="index"
              label="序号"
              width="80"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="orderNo"
              label="订单号"
              align="center"
              width="200"
            />
            <el-table-column
              prop="productName"
              label="产品名称"
              align="center"
            />
            <el-table-column
              prop="orderPayPrice"
              label="订单价格"
              align="center"
            >
              <template #default="scope">
                {{ `${scope.row.orderPayPrice}元` }}
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" align="center">
            </el-table-column>
            <el-table-column label="状态" align="center">
              <template #default="scope">
                <el-tag :type="getOrderStatusInfo(scope.row.state).type">
                  {{ getOrderStatusInfo(scope.row.state).msg }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="280" align="center">
              <template #default="scope">
                <el-button type="primary" @click="handleGoto(scope.row)"
                  >查看订单</el-button
                >
                <el-button
                  v-if="scope.row.state === 10"
                  type="danger"
                  @click="handleRefund(scope.row)"
                >
                  订单退款
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="totalProducts"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
        </el-card>
      </div>
    </div>

    <!-- 退款弹窗 -->
    <el-dialog
      v-model="refundDialogVisible"
      title="选择退款时间段"
      width="500px"
    >
      <el-select
        v-model="selectedTimeSlotId"
        placeholder="请选择退款时间段"
        style="width: 100%"
      >
        <el-option
          v-for="timeSlot in availableTimeSlots"
          :key="timeSlot.id"
          :label="formatTimeRange(timeSlot.startTime, timeSlot.endTime)"
          :value="timeSlot.id"
        />
      </el-select>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="refundDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRefund">确认退款</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { useRouter } from 'vue-router';
import {
  ElButton,
  ElCard,
  ElInput,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElMessage,
  ElTag,
  ElSelect,
  ElOption,
  ElDialog,
} from 'element-plus';
import { IconifyIcon } from '@vben/icons';
import { getOrderList, type orderApi, refundOrder } from '#/api/order';

// 定义订单状态枚举
const ORDER_STATUS = {
  UNPAID: { state: 1, msg: '待支付', type: 'warning' },
  CANCELED: { state: 5, msg: '已取消', type: 'info' },
  TO_REDEMPTION: { state: 10, msg: '待核销', type: 'primary' },
  REFUND: { state: 15, msg: '已退款', type: 'danger' },
  REDEMPTION: { state: 20, msg: '已核销', type: 'success' },
  EXPIRED: { state: 25, msg: '已过期', type: 'info' },
} as const;

const router = useRouter();

// 状态管理
const searchKeyword = ref('');
const tableLoading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const totalProducts = ref(0);
const tableData = ref<orderApi.listItem[]>([]);
const filterState = ref<number | null | undefined>(null);

// 退款相关状态
const refundDialogVisible = ref(false);
const selectedTimeSlotId = ref<string>('');
const currentRefundOrder = ref<orderApi.listItem | null>(null);

// 监听pageSize变化，重置currentPage为1并重新加载数据
watch(pageSize, (newSize) => {
  currentPage.value = 1; // 页码重置为1
});

// 监听currentPage变化，重新加载数据
watch(currentPage, (newPage) => {
  loadProducts();
});

// 计算可用的时间段（状态为10的）
const availableTimeSlots = computed(() => {
  if (!currentRefundOrder.value?.priceDateTimeRangeVOList) {
    return [];
  }

  return currentRefundOrder.value.priceDateTimeRangeVOList.filter(
    (timeSlot) => timeSlot.state === 10,
  );
});

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1; // 搜索时重置页码
  loadProducts();
};

// 重置筛选
const resetFilters = () => {
  searchKeyword.value = '';
  filterState.value = null;
  currentPage.value = 1;
  loadProducts();
};

const handleGoto = (row?: orderApi.listItem | undefined) => {
  if (row && row.orderNo) {
    router.push(`/order/detail/${row.orderNo}`);
  }
};

// 处理退款按钮点击
const handleRefund = (row: orderApi.listItem) => {
  currentRefundOrder.value = row;
  if (row.priceDateTimeRangeVOList && row.priceDateTimeRangeVOList.length > 0) {
    const availableSlots = row.priceDateTimeRangeVOList.filter(
      (slot) => slot.state === 10,
    );
    selectedTimeSlotId.value =
      availableSlots.length > 0 ? availableSlots[0].id : '';
  } else {
    selectedTimeSlotId.value = '';
  }
  refundDialogVisible.value = true;
};

// 格式化时间范围显示
const formatTimeRange = (startTime: string, endTime: string) => {
  const start = startTime.split(' ')[1].substring(0, 5);
  const end = endTime.split(' ')[1].substring(0, 5);
  return `${start}-${end}`;
};

// 确认退款
const confirmRefund = async () => {
  if (!selectedTimeSlotId.value) {
    ElMessage.warning('请选择退款时间段');
    return;
  }

  try {
    // 调用退款接口
    const res = await refundOrder(selectedTimeSlotId.value);
    if (res.code === 200) {
      ElMessage.success('退款申请已提交,预计1-3个工作日处理完成!');
      refundDialogVisible.value = false;

      // 重新加载数据
      loadProducts();
    } else {
      ElMessage.error('退款操作失败: ' + res.message);
    }
  } catch (error) {
    console.error('退款失败:', error);
    ElMessage.error('退款操作失败');
  }
};

// 加载订单数据
const loadProducts = async () => {
  tableLoading.value = true;
  try {
    const {
      data: { list, total },
    } = await getOrderList({
      orderNo: searchKeyword.value,
      state: filterState.value ?? undefined,
      pageNum: currentPage.value, // 传递当前页码
      pageSize: pageSize.value, // 传递每页条数
    });
    totalProducts.value = Number(total);
    tableData.value = list;
  } catch (error) {
    console.error('加载订单失败:', error);
    tableData.value = [];
    totalProducts.value = 0;
    ElMessage.error('加载订单数据失败');
  } finally {
    tableLoading.value = false;
  }
};

// 获取订单状态信息
const getOrderStatusInfo = (state: number) => {
  for (const status of Object.values(ORDER_STATUS)) {
    if (status.state === state) {
      return status;
    }
  }
  // 默认返回禁用状态
  return { state: 0, msg: '禁用', type: 'info' };
};

// 页面加载时获取数据
loadProducts();
</script>

<style scoped lang="scss">
.product-list-container {
  padding: 20px;
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    .page-title {
      font-size: 20px;
      font-weight: 600;
      margin: 0;
    }
    .actions {
      display: flex;
      gap: 10px;
    }
  }
  .pagination-container {
    margin-top: 16px;
    text-align: right;
  }

  .filter-card {
    margin-bottom: 20px;

    .filter-group {
      display: flex;
      gap: 15px;
      align-items: center;
      flex-wrap: wrap;

      .search-input {
        width: 300px;
      }

      .status-filter {
        width: 200px;
      }
    }
  }
}
</style>
